﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace baselib
{



    public class WebapiHelp
    {


        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="uniquename"></param>
        /// <param name="FileName">相对路径 ,可能包含子文件夹</param>
        /// <param name="directory"></param>
        /// <param name="UpdateDownloadPercent"></param>
        public static void DownLoadFile(string url, string uniquename,string FileName,string directory,Action<int> UpdateDownloadPercent=null)
        {
            try
            {
                url += $"?FileName={FileName}&UniqueName={uniquename}";

                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "Get";
                request.Accept = "text/html, application/x-msdownload, */*";


                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        string filepath = directory + "\\" + FileName;
                        string folder = Path.GetDirectoryName(filepath);
                        if (!Directory.Exists(folder))
                        {
                            Directory.CreateDirectory(folder);
                        }
                        using (Stream stream = new FileStream(directory + "\\" + FileName, FileMode.Create))
                        {
                            byte[] bArr = new byte[1024];
                            int size;
                            while ((size = responseStream.Read(bArr, 0, bArr.Length)) > 0)
                            {
                                stream.Write(bArr, 0, size);

                                UpdateDownloadPercent?.Invoke(size);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {

                MessageBox.Show(e.Message);
            }


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url">webapi地址</param>
        /// <param name="filepath">要上传文件的本地路径</param>
        /// <param name="UniqueName">上传到服务器后放置的文件夹名称，以此区分不同的程序</param>
        public static void UpdateLoadFile(string url, string filepath, string UniqueName,string RelitivePath="")
        {
            try
            {
                if (!File.Exists(filepath))
                {
                    MessageBox.Show("没找到文件" + filepath);
                    return;
                }
                WebClient webClient = new WebClient();
                webClient.Credentials = CredentialCache.DefaultCredentials;
                webClient.Headers.Add("Content-Type", "application/form-data");//注意头部必须是form-data
                webClient.QueryString["UniqueName"] = UniqueName;
                webClient.QueryString["RelitivePath"] = RelitivePath;
            
                byte[] fileb = webClient.UploadFile(url, "Post", filepath);               
                string response = Encoding.UTF8.GetString(fileb);

                Console.WriteLine(response);
            }
            catch (Exception e)
            {

                MessageBox.Show(e.Message);

            }

        }


        

        public static async void UploadFile(string url, string filepath, string UniqueName, string RelitivePath = "")
        {
            try
            {
                if (!File.Exists(filepath))
                {
                    MessageBox.Show("没找到文件" + filepath);
                    return;
                }
                WebClient webClient = new WebClient();
                webClient.Credentials = CredentialCache.DefaultCredentials;
                webClient.Headers.Add("Content-Type", "application/form-data");//注意头部必须是form-data
                webClient.QueryString["UniqueName"] = UniqueName;
                webClient.QueryString["RelitivePath"] = RelitivePath;

                byte[] fileb = await webClient.UploadFileTaskAsync(url, "Post", filepath);
                string response = Encoding.UTF8.GetString(fileb);

                Console.WriteLine(response);
            }
            catch (Exception e)
            {

                MessageBox.Show(e.Message);

            }

        }





        public static string CheckNeedUpload(string url,string json)
        {
            WebClient webClient = new WebClient();
            webClient.Credentials = CredentialCache.DefaultCredentials;
            webClient.Headers.Add("Content-Type", "application/json;charset:utf-8");
           
            webClient.Headers.Add("Accept-Charset", "utf-8");
            webClient.Encoding = Encoding.UTF8;
            return webClient.UploadString(url,"Post", json);
        }


        public static string HttpGetRequest(string url)
        {

            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "Get";
                //request.Accept = "text/plain";


                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader rd = new StreamReader(responseStream))
                        {
                            return rd.ReadToEnd();
                        }
                    }
                }
                return null;
            }
            catch (Exception e)
            {

                MessageBox.Show(e.Message);
                return null;
            }

        }
    }

    public class DownFileInfo
    {
        public string UserID { get; set; }
        public string Passwd { get; set; }
        public string FileName { get; set; }
    }


    public static class PathHelper
    {

        //C:\Users\chenzd\Desktop\AutoUpdateTest\堆场\text.txt
        //C:\Users\chenzd\Desktop\AutoUpdateTest\堆场\AutoUpdate\tst.txt
        //去掉folderpath获得相对路径
        public static string GetRelitivePath(string filepath, string rootdirectory)
        {
            if (!rootdirectory.EndsWith("\\"))
            {
                rootdirectory += "\\";
            }
            return filepath.Replace(rootdirectory, "");



        }
    }

    public class LogHelper
    {
        public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
        public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
        public static void WriteInfo(string info)
        {
            if (loginfo.IsInfoEnabled)
            {
                loginfo.Info(info);
            }
        }
        public static void WriteDebug(string info)
        {
            if (loginfo.IsDebugEnabled)
            {
                loginfo.Debug(info);
            }
        }
        public static void WriteError(string info, Exception ex)
        {
            if (logerror.IsErrorEnabled)
            {
                logerror.Error(info, ex);
            }
        }
    }


}
